package com.agileai.esb.smc.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.jasig.cas.client.authentication.AttributePrincipal;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.esb.smc.bizmoduler.sysres.SysUserManage;
import com.agileai.esb.smc.domain.User;
import com.agileai.hotweb.common.BeanFactory;
import com.agileai.hotweb.domain.core.Profile;

public class XGeneralCasFilter implements Filter {

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest httpRequest = (HttpServletRequest) request;
		AttributePrincipal attributePrincipal = (AttributePrincipal) httpRequest
				.getUserPrincipal();
		if (attributePrincipal != null) {
			String loginName = attributePrincipal.getName();
			Profile profile = getProfile(httpRequest);
			if (profile == null) {
				BeanFactory beanFactory = BeanFactory.instance();
				SysUserManage userManage = (SysUserManage) beanFactory
						.getBean("sysUserManageService");
				DataRow recordRow = userManage.getRecordByCode(new DataParam(
						"USER_CODE", loginName));
				initAuthedUser(httpRequest, recordRow);
			}
		}
		chain.doFilter(request, response);
	}
	
	private void initAuthedUser(HttpServletRequest request, DataRow recordRow) {
		User user = new User();
		String userId = String.valueOf(recordRow.get("USER_CODE"));
		String userName = String.valueOf(recordRow.get("USER_NAME"));
		user.setUserId(userId);
		user.setUserName(userName);
		String fromIpAddress = request.getLocalAddr();
		Profile profile = new Profile(userId, fromIpAddress, user);
		request.getSession(true).setAttribute(Profile.PROFILE_KEY, profile);
	}
	
	private Profile getProfile(HttpServletRequest request) {
		Profile profile = null;
		HttpSession session = request.getSession(false);
		if (session != null) {
			profile = (Profile) session.getAttribute(Profile.PROFILE_KEY);
		}
		return profile;
	}

	@Override
	public void destroy() {}

	@Override
	public void init(FilterConfig arg0) throws ServletException {}
}
